/*
*
* _c() => createElement()
* _v() => createTextNode()
* _s() => {{name}} =>  _s(name)
*
  */
/*
function render() {
  return `_c('div',{id: "app", style: { "color": "red","font-size": "20px"}),_v("您好","+s(name)")`
} 
*/


const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;

function formatProps(attrs) {
  let str = ''
  for (var i = 0; i < attrs.length; i++) {
    let attr = attrs[i]
    if (attr[name] === 'style') {
      let styleAttrs = {}
      attr.value.split(';').map((styleAttr) => {
        let [key, value] = styleAttr.split(':')
        styleAttr[key] = value
      })
      attr.value = styleAttrs
    }
    str += `${attr.name}:${JSON.stringify(attr.value)}`
  }
  console.log(`
{${str.slice(0, -1)}}
`)
  return `{${str.slice(0, -1)}}`
}

function generateChild(node) {
  console.log(`进来`)
  if (node.type === 1) {
    return generate(node)
  } else if (node.type === 3) {
    console.log({
      text: node.text
    })
    let text = node.text
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`
    }

    let match,
      index,
      lastIndex = defaultTagRE.lastIndex = 0,
      textArr = []
    while (match = defaultTagRE.exec(text)) {
      index = match.index
      if (index > lastIndex) {
        textArr.push(JSON.stringify(text.slice(lastIndex, index)))
      } else {
        textArr.push(`s(${match[1].trim()})`)
        lastIndex = index + match[0].length
      }
      if (lastIndex < text.length) {
        textArr.push(JSON.stringify(text.slice(lastIndex)))
      }
    }

    console.log(111)
    console.log(`_v(${textArr.join('+')})`)
    return `_v(${textArr.join('+')})`
  }
}

function getChildren(el) {
  console.log(222)
  console.log(el)
  const children = el.children
  if (children) {
    console.log(333)
    return children.map(c => generateChild(c)).join(',')
  }
}
function generate(el) {
  let children = getChildren(el)
  let code = `
  _c('${el.tag}',${el.attrs.length > 0
      ?
      `${formatProps(el.attrs)}`
      : 'undefined'
    }${children ? `,${children}` : ''
    })
`
  console.log({
    code
  })
  return code
}

export {
  generate
}
